package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import io.swagger.annotations.Api;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/blow")
@Api(value = "代理访问", tags = "代理访问")
public class ProxyController {

    // 目标API地址（根据实际需求可配置到application.properties中）
    private static final String TARGET_URL =
            "https://hqfw.swpu.edu.cn/api/auth/login/tripartite/getOPenIdByAccount";

    private final RestTemplate restTemplate = new RestTemplate();

    @GetMapping("/proxy/getOpenId")
    public ApiResponse proxyGetOpenId(@RequestParam("account") String account) {
        try {
            // 1. 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 2. 构建表单参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("account", account);

            // 3. 创建HTTP实体
            HttpEntity<MultiValueMap<String, String>> requestEntity =
                    new HttpEntity<>(params, headers);

            // 4. 发送POST请求到目标接口
            ResponseEntity<String> response = restTemplate.exchange(
                    TARGET_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            // 5. 将目标接口的响应直接返回给前端
            return ApiResponse.success(response.getBody());

        } catch (Exception e) {
            return ApiResponse.success(e.getMessage());
        }
    }
}
